﻿using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Input;
using Security.Domain;
using Security.Events;
using Security.Events.Commands;
using Security.Helpers;
using Security.Specs.DataLayer;
using Security.Specs.Implementation.Common;
using Security.Specs.Reports;

namespace Security.Specs.Implementation.NodeRoots
{
    [Export(typeof(SecurityNodeReportBase)), SecurityNodeRootMetadata(typeof(Department),(int) SecurityRootNodeOrder.Departments)]
    public class DepartmentSecurityNodeRoot : SecurityNodeReport
    {
        private readonly EventBroker eventBroker;
        private readonly ISecurityDataModel model;

        [ImportingConstructor]
        public DepartmentSecurityNodeRoot(EventBroker eventBroker, ISecurityDataModel model) :
            base(Strings.GetRootNodeDescription(typeof(Department)), typeof(Department))
        {
            this.eventBroker = eventBroker;
            this.model = model;

            nodes.Add(Empty());
            Subscribe();
        }

        private void Subscribe()
        {
            eventBroker.OfType<ChangesCommittedCommand>().
                Where(c => c.Type == typeof (Department)).
                Subscribe(OnChangesCommited);
        }

        private void OnChangesCommited(ChangesCommittedCommand command)
        {
            ChildNodesCollectionNeeded();
        }

        protected override void ChildNodesCollectionNeeded()
        {
            nodes.Clear();
            foreach (var department in model.Departments.OrderBy(d => d.Name).ToArray())
            {
                nodes.Add(new SecurityNodeReport(department.Name, department));
            }
        }
    }
}
